package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.ObjectUtils;

import java.io.IOException;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeAdapterImpl extends TypeAdapter<Time> {

	@Override
	public void write(JsonWriter out, Time value) throws IOException {
		DateFormat format = new SimpleDateFormat("HH:mm:ss");
		String dateFormatAsString="";
		if(ObjectUtils.isNotEmpty(value)){
			dateFormatAsString = format.format(new Date(value.getTime()));
		}
		out.value(dateFormatAsString);
	}

	@Override
	public Time read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			return null;
		}
		try {
			DateFormat format = new SimpleDateFormat("HH:mm:ss");
			Date date = format.parse(in.nextString());
			return new Time(date.getTime());
		} catch (ParseException e) {
			throw new JsonParseException(e);
		}		
	}

}
